package br.com.manutencaocarro.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import br.com.manutencaocarro.R;
import br.com.manutencaocarro.dao.PecaDAO;
import br.com.manutencaocarro.helper.CadastroPecaHelper;
import br.com.manutencaocarro.modelo.Peca;

public class CadastraPecaActivity extends Activity 
{
	private CadastroPecaHelper helper;
	private Peca pecaSelecionada;
	private boolean detalhar;
	private int idPeca;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cadastro_peca);
		detalhar = false;

		Intent intent = getIntent();
		
		if( intent != null )
		{
			if( intent.getSerializableExtra(getString(R.string.pecaselecionada)) != null )
			{
				pecaSelecionada = (Peca) intent.getSerializableExtra(getString(R.string.pecaselecionada));
				idPeca = pecaSelecionada.getId();
			}
			
			if( intent.getSerializableExtra(getString(R.string.detalhar)) != null )
			{
				detalhar = (Boolean) intent.getSerializableExtra(getString(R.string.detalhar));
			}
		}
		
		helper = new CadastroPecaHelper(this);
	}

	@Override
	protected void onResume() 
	{
		super.onResume();
		Button botao = (Button) findViewById(R.id.cadastrar_peca);
		
		if( pecaSelecionada != null )
		{
			botao.setText(R.string.atualizar);
			helper.colocaPecaNoFormulario( this, pecaSelecionada);
		}

		if( detalhar )
		{
			helper.setReadOnly();
			botao.setVisibility(android.view.View.INVISIBLE);
		}
		
		botao.setOnClickListener( new OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				Peca peca = helper.pegaPecaCadastro();
				PecaDAO dao = new PecaDAO(CadastraPecaActivity.this);
				if( pecaSelecionada != null )
				{
					peca.setId(idPeca);
					dao.atualiza(peca);
				} else {
					dao.cadastraPeca(peca);
				}
				
				dao.close();

				finish();
			}
		});
	}
}